package com.group.controller;

import com.group.model.Student;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @author lenovo
 */
public class StudentController {
    private static Map<String, Student> studentMap = new HashMap<>();
    private static int counter = 200000;
    public static String generateId() {
        for (counter=200000;true;counter++){
            if(studentMap.get("2024"+counter)==null){
                break;
            }
        }
        return "2024" + counter;
    }

    public static void addOnlyMap(Student s) {
        studentMap.put(s.getId(), s);
    }//用于只添加到内存中，例如模拟数据时使用

    public static void addStudent(Student s) {
        studentMap.put(s.getId(), s);
        try {
            saveToFile("saveStudents.txt");
        } catch (Exception e) {
            //
        }
    }
    public static void deleteStudent(Student s){
        studentMap.remove(s.getId());
        try {
            saveToFile("saveStudents.txt");
        } catch (Exception e) {
            //
        }
    }
    public static Student get(String id) { return studentMap.get(id); }
    public static Collection<Student> getAll() { return studentMap.values(); }

    public static void saveToFile(String path) throws IOException {
        //throws IOException：表示如果写文件失败（如磁盘满、权限不足），会抛出输入输出异常
        try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path), StandardCharsets.UTF_8))) {
            writer.write("");
            //写一个空字符串，可以理解为**“显式清空文件内容”**；
            for (Student s : getAll()) {writer.write(s.toText() + "\n");}
        }
        /*
         FileOutputStream(path)打开一个文件输出流，如果文件不存在就创建，如果存在就会清空原内容；
         path 就是文件路径 "saveStudents.txt"。
         OutputStreamWriter(...)把字节流 FileOutputStream 转换为 字符流，用来写文字（不是二进制）；
         使用编码格式：StandardCharsets.UTF_8，可以正确写入中文等字符。
         BufferedWriter(...)加一个缓冲层，提升写入效率；把多个字符先存进内存缓存，然后一起写入文件，减少磁盘操作。
        */
    }

    public static void deleteAll(String path) throws IOException{
        try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path), StandardCharsets.UTF_8))) {
            writer.write("");
        }

        studentMap.clear();
    }

    public static void saveToFileOrder(String path) throws IOException {
        List<Student> sortedList = new ArrayList<>(StudentController.getAll());
        sortedList.sort((s1, s2) -> Double.compare(
                getTotalScore(s2), getTotalScore(s1))
        );//将所有学生转为列表，并将其排序，按总分从高到低排序
        try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path), StandardCharsets.UTF_8))) {
            writer.write("");
            for (Student s : sortedList) {
                String line = String.format("%.1f",getTotalScore(s));
                writer.write(s.toText() + "\t" + "total:" +line+ "\n");
                //每行写：学生基本信息 + 总分
            }
        }
    }

    private static double getTotalScore(Student s) {
        Map<String, Double> scores = s.getScores();
        return scores.getOrDefault("Math", 0.0)
                + scores.getOrDefault("Java", 0.0)
                + scores.getOrDefault("PE", 0.0);
    }

    public static void deleteAllOnlyMap(){
        studentMap.clear();
    }
}
